<?php
/**
 * +--------------------------------------------------------+
 * @Created by Phpstorm.
 * @Category ExceptionError.php
 * @Depiction
 * @Author hwy <429208948@qq.com>
 * @Date 2022/3/22  17:11
 * +--------------------------------------------------------+
 */

namespace App\Models;


use Carbon\Carbon;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Str;

class ExceptionError extends BaseModel
{
    /**
     * 指示模型主键是否递增
     *
     * @var bool
     */
    public $incrementing = false;
    /**
     * 自动递增ID的“类型”。
     *
     * @var string
     */
    protected $keyType = 'string';

    /**
     * 可以被批量赋值的属性。
     *
     * @var array
     */
    protected $fillable = [
        'message', 'code', 'file', 'line', 'trace', 'trace_as_string', 'is_solve',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'line'     => 'integer',
        'is_solve' => 'boolean',
    ];

    /**
     * Bootstrap the model and its traits.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

        ExceptionError::creating(function ($model) {
            $model->setId();
        });
    }

    /**
     * 设置ID
     */
    public function setId()
    {
        $this->attributes['id'] = Str::orderedUuid();
    }

    public function getId()
    {
        return $this->attributes['id'];
    }

    /**
     * Json转数组
     * @param $value
     * @return mixed
     */
    public function getTraceAttribute($value)
    {
        return json_decode($value, true);
    }

    /**
     * 数字转Json
     * @param $value
     */
    public function setTraceAttribute($value): void
    {
        $this->attributes['trace'] = json_encode($value);
    }

    /**
     * 自定义异常字符串
     *
     * @param $value
     */
    public function setTraceAsStringAttribute($value): void
    {
        $this->attributes['trace_as_string'] =
            '[' . Carbon::now()->format('Y-m-d H:i:s') . '] ' . App::environment() . '.ERROR: '
            . $this->attributes['message']
            . ' at ' . $this->attributes['file'] . ':' . $this->attributes['line']
            . "\n"
            . $value;
    }
}
